#include "headers/LoginDialog.h"
#include <QMessageBox>

LoginDialog::LoginDialog(AuthClient *authClient, EmailSender *emailSender, QWidget *parent)
    : QDialog(parent),
    ui(new Ui::LoginDialog),
    m_authClient(authClient),
    m_emailSender(emailSender),
    m_loginSuccess(false)
{
    ui->setupUi(this);
    connect(ui->loginBtn, &QPushButton::clicked, this, &LoginDialog::onLoginClicked);
    connect(ui->registerBtn, &QPushButton::clicked, this, &LoginDialog::onRegisterClicked);
    connect(ui->forgotPwdBtn, &QPushButton::clicked, this, &LoginDialog::onForgotPwdClicked);
}

void LoginDialog::onLoginClicked()
{
    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请填写用户名和密码");
        return;
    }

    if (m_authClient->loginUser(username, password)) {
        m_loginSuccess = true;
        accept();
    } else {
        QMessageBox::warning(this, "登录失败", "用户名或密码错误");
    }
}

void LoginDialog::onRegisterClicked()
{
    RegisterDialog regDialog(m_authClient, m_emailSender, this);
    regDialog.exec();
}

void LoginDialog::onForgotPwdClicked()
{
    QMessageBox::information(this, "忘记密码", "请联系管理员重置密码");
}

bool LoginDialog::isLoginSuccess() const
{
    return m_loginSuccess;
}
